<?php

namespace app\admin\controller\kzvote;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 投票活动报名人员管理
 *
 * @icon fa fa-circle-o
 */
class Person extends Backend
{

    /**
     * Person模型对象
     * @var \app\common\model\kzvote\Person
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\kzvote\Person;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        require_once ROOT_PATH . 'addons/kzvote/helper.php';

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        $vote_id = $this->request->param('vote_id','');
        $this->assignconfig('vote_id',$vote_id);
        if ($vote_id){
            $this->model->where('vote_id',$vote_id);
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['vote','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                if ($row['video']) {
                    $row['video'] = cdnurl($row['video'],false, true);
                }
                $row->getRelation('vote')->visible(['name','gift_status']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $this->dataLimit = 'auth';//管理员添加的需要设置$this->dataLimitField字段的值
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $images          = explode(",", $params['images']);
                    $params['image'] = $images[0];
                    $params['er_code']   = '';
                    $result = $this->model->allowField(true)->save($params);
                    kzvote_qrCode($this->model, $this->model->id, 'pages/vote/person');

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $vote_id = $this->request->param('vote_id');
        $group = (new \app\common\model\kzvote\Group)->where('vote_id',$vote_id)->order('code desc')->select();
        $this->view->assign('vote_id',$vote_id);
        $this->view->assign('group',$group);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $images          = explode(",", $params['images']);
                    $params['image'] = $images[0];

/*
                    if($row['status'] == '10' && $params['status'] == '20'){
                        $count = $this->model
                            ->where(['vote_id' => $row['vote_id']])
                            ->where('status','20')->count();
                        $params['code'] = $count + 1;
                    }
*/

                    $result = $row->allowField(true)->save($params);
                    if (!$row->er_code){
                        //生成小程序二维码
                        kzvote_qrCode($row, $row['id'], 'pages/vote/person');
                    }
                    Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $group = (new \app\common\model\kzvote\Group)->where('vote_id',$row['vote_id'])->order('code desc')->select();
        $this->view->assign('group',$group);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 导出
     */
    public function export(){
        $this->relationSearch = true;

        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');

            $whereIds = $ids == 'all' ? '1=1' : ['person.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => json_encode($filter), 'op' => json_encode($op)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //设置过滤方法
            $this->request->filter(['strip_tags']);

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //开始制作表格
            $spreadsheet = new Spreadsheet();
            $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $spreadsheet->getDefaultStyle()->getFont()->setSize(12);
            $spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
            $spreadsheet->getDefaultStyle()->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
            $spreadsheet->getActiveSheet()->getStyle('L')->getAlignment()->setWrapText(true);

            $worksheet = $spreadsheet->setActiveSheetIndex(0);

            $file_name = '作品导出'.date('Y-m-d H:i:s',time());

            $worksheet->getCell('A1')->setValue('序号');
            $worksheet->getCell('B1')->setValue('作品编号');
            $worksheet->getCell('C1')->setValue('作品名称');
            $worksheet->getCell('D1')->setValue('微信昵称');
            $worksheet->getCell('E1')->setValue('用户标识');
            $worksheet->getCell('F1')->setValue('手机号');
            $worksheet->getCell('G1')->setValue('票数');
            $worksheet->getCell('H1')->setValue('分组名称');
            $worksheet->getCell('I1')->setValue('审核状态');
            $worksheet->getCell('J1')->setValue('报名类型');
            $worksheet->getCell('K1')->setValue('报名时间');
            $worksheet->getCell('L1')->setValue('报名选项');

            $ABC = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K','L'];

            $list = $this->model->alias('person')
                ->with(['user'])
                ->where($whereIds)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $arr = [];
            foreach ($list as $key => $val) {

                $option = '';
                if ($val['option']){
                    foreach ($val['option'][0] as $k=>$row){
                        $option .= $k.":".$row."​\n​";
                    }
                }

                $data = array(
                    $val['id'],
                    $val['code'],
                    $val['name'],
                    $val['user']['nickname'],
                    $val['user_id'] ? "用户-{$val['user_id']}" : "管理员-{$val[$this->dataLimitField]}",
                    $val['user']['mobile'],
                    $val['count'],
                    $val['group_name'],
                    $val['status_text'],
                    $val['type_text'],
                    date('Y-m-d H:i:s',$val['createtime']),
                    $option
                );

                array_push($arr, $data);
            }

            foreach ($arr as $key => $row) {
                foreach ($ABC as $k => $r) {
                    if(in_array($r, ['F'])){
                        $worksheet->getCell($ABC[$k] . ($key + 2))->setValueExplicit($row[$k], 's');
                    }else{
                        $worksheet->getCell($ABC[$k] . ($key + 2))->setValue($row[$k]);
                    }
                }
            }
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
            //下载文档
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $file_name . '.xlsx"');
            header('Cache-Control: max-age=0');
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
        }
    }

}
